// pages/changeUserInfo/changeUserInfo.js

import { createStoreBindings } from 'mobx-miniprogram-bindings';
import { store } from '../../store/store';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    newNickName: null,
    urlUpload: '/portal/icons/upLoad',
    urlSubmit: '/portal/user/changeInfo',
    fileListHead: [],
  },

  onChangeNickname(e) {
    this.setData({
      newNickName: e.detail
    })
  },

  afterReadHead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: this.data.urlUpload, // 仅为示例，非真实的接口地址
      filePath: file.url,
      method: 'POST',
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        console.log(res);
        // 上传完成需要更新 fileList
        const { fileListHead = [] } = this.data;
        fileListHead.push({ ...file, url: res.data});
        this.setData({ fileListHead });
        console.log(this.data.fileListHead);
      },
    });
  },

  deleteImgHead(event) {
    let list = this.data.fileListHead;
    list.splice(event.detail.index, 1);
    this.setData({
      fileListHead: list,
    });
  },

  submit() {
    let name = null;
    if (this.data.fileListHead.length != 0) {
      name = this.data.fileListHead[0].url;
      name = name.split('/');
      name = name[name.length - 1];
    }
    
    Dialog.confirm({
      message: '确认修改',
    })
      .then(() => {
        // on confirm
        wx.request({
          url: this.data.urlSubmit,
          method: "POST",
          data: {
            userId: this.getUser().id,
            newNickname: this.data.newNickName,
            newHead: name,
          },
          success: (res) => {
            Toast(res.data.msg);
            setTimeout(()=>
              {
                // 大括号里放需要延迟执行的代码
                wx.navigateBack({
                  delta: 1
                });
              }, 1000)
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      urlUpload: this.getWebsite() + this.data.urlUpload,
      urlSubmit: this.getWebsite() + this.data.urlSubmit,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 销毁挂载绑定
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})